//
//  YSBatteryView.m
//  YSBookRead
//
//  Created by MOLBASE on 2018/11/8.
//  Copyright © 2018年 YangShen. All rights reserved.
//

#import "YSBatteryView.h"

#define kBatterySize CGSizeMake(25, 10)
/// 电池量宽度 跟图片的比例
#define kBatteryLevelViewW 20
#define kBatteryLevelViewScale (kBatteryLevelViewW / kBatterySize.width)

@interface YSBatteryView ()
/// 电量
@property (nonatomic, strong) UIView *batteryLevelView;
@end

@implementation YSBatteryView

- (instancetype)initWithFrame:(CGRect)frame {
    frame = CGRectMake(0, 0, kBatterySize.width, kBatterySize.height);
    if (self = [super initWithFrame:frame]) {
        [self setupSubViews];
    }
    return self;
}

- (void)setupSubViews {
    // 进度
    self.batteryLevelView = [[UIView alloc] init];
    self.batteryLevelView.layer.masksToBounds = YES;
    [self addSubview:self.batteryLevelView];

    // 设置样式
    self.image = [[UIImage imageNamed:@"G_Battery_Black"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.backColor = [UIColor whiteColor];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    CGFloat spaceW = (self.frame.size.width / kBatterySize.width) * kBatteryLevelViewScale;
    CGFloat spaceH = (self.frame.size.height / kBatterySize.height) * kBatteryLevelViewScale;

    CGFloat batteryLevelViewY = 2.1 * spaceH;
    CGFloat batteryLevelViewX = 1.4 * spaceW;
    CGFloat batteryLevelViewH = self.frame.size.height - 3.4 * spaceH;
    CGFloat batteryLevelViewW = self.frame.size.width * kBatteryLevelViewScale;
    CGFloat batteryLevelViewWScale = batteryLevelViewW / 100;

    // 判断电量
    CGFloat tempBatteryLevel = self.batteryLevel;
    if (self.batteryLevel < 0) {
        tempBatteryLevel = 0;
    } else if (self.batteryLevel > 1) {
        self.batteryLevel = 1;
    }

    self.batteryLevelView.frame = CGRectMake(batteryLevelViewX, batteryLevelViewY, (tempBatteryLevel * 100) * batteryLevelViewWScale, batteryLevelViewH);
    self.batteryLevelView.layer.cornerRadius = batteryLevelViewH * 0.125;
}

#pragma mark - Setter
- (void)setBackColor:(UIColor *)backColor {
    _backColor = backColor;
    self.batteryLevelView.backgroundColor = backColor;
}

- (void)setBatteryLevel:(CGFloat)batteryLevel {
    _batteryLevel = batteryLevel;
    [self setNeedsLayout];
}

@end
